using System.Collections.Generic;
using Godot;

namespace Arcane.Source.UI
{
    public partial class RecyclerContainer : Container
    {
        private IAdapter _adapter = null;
        public IAdapter Adapter
        {
            get => _adapter;
            set
            {
                _adapter = value;
                ClearAll();
                UpdateElements();
            }
        }

        private readonly Stack<Control> _pool = [];

        protected virtual void UpdateElements()
        {
            
        }

        protected void ClearAll()
        {
            foreach (var child in GetChildren()) child.QueueFree();
            while (_pool.Count > 0) _pool.Pop().QueueFree();
        }

        protected void Recycle(Node child)
        {
            if (child.GetParent() != this || child is not Control ctrl)
            {
                child.QueueFree();
                return;
            }

            _pool.Push(ctrl);
            RemoveChild(ctrl);
        }

        protected Control Obtain(int position)
        {
            var element = _pool.Count > 0 ? _pool.Pop() : _adapter.CreateElement();
            _adapter.BindElement(element, position);
            return element;
        }
    }
}